<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button @click="addUserInfo = true" type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="rolesList" stripe border>
        <el-table-column type="expand" label="展开">
          <template slot-scope="scope">
            <el-row
              :class="['bdbtm', i1 === 0 ? 'bdtop' : '']"
              v-for="(item, i1) in scope.row.children"
              :key="item.id"
            >
              <el-col :span="5">
                <el-tag closable @close="delUserRoles(scope.row, item.id)">{{
                  item.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop']"
                  v-for="(item1, i2) in item.children"
                  :key="item1.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="delUserRoles(scope.row, item1.id)"
                      >{{ item1.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      closable
                      type="warning"
                      v-for="item2 in item1.children"
                      :key="item2.id"
                      @close="delUserRoles(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini"
              @click="editRoles(scope.row.id)">编辑</el-button
            >
            <el-button type="danger" icon="el-icon-delete" size="mini"
              @click="delRoles(scope.row.id)">删除</el-button
            >
            <el-button type="warning" icon="el-icon-setting" size="mini"
              @click="rolesDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 对话框 -->
    <el-dialog
  title="权限分配"
  :visible.sync="dialogVisible"
  width="50%" @close="dialogClose">
  <el-tree show-checkbox node-key="id" ref="treeRef" default-expand-all :default-checked-keys="defKeys" :data="rightList" :props="rightsTree"></el-tree>
  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="dialogTreeInfo">确 定</el-button>
  </span>
</el-dialog>
<!-- 添加角色对话框 -->
<el-dialog
  title="添加角色"
  :visible.sync="addUserInfo"
  width="50%"
  @close="addRolesClose">
  <el-form :model="addForm" ref="addFormRef" label-width="70px">
    <el-form-item label="角色名称">
        <el-input v-model="addForm.roleName"></el-input>
      </el-form-item>
      <el-form-item label="角色描述">
        <el-input v-model="addForm.roleDesc"></el-input>
      </el-form-item>
  </el-form>
  <span slot="footer">
    <el-button @click="addUserInfo = false">取 消</el-button>
    <el-button type="primary" @click="addUser">确 认</el-button>
  </span>
</el-dialog>
<!-- 编辑角色对话框 -->
<el-dialog
  title="编辑角色"
  :visible.sync="editUserInfo"
  width="50%"
  @close="editRolesClose">
  <el-form :model="editForm" ref="editFormRef" label-width="70px">
    <el-form-item label="角色名称">
        <el-input v-model="editForm.roleName"></el-input>
      </el-form-item>
      <el-form-item label="角色描述">
        <el-input v-model="editForm.roleDesc"></el-input>
      </el-form-item>
  </el-form>
  <span slot="footer">
    <el-button @click="editUserInfo = false">取 消</el-button>
    <el-button type="primary" @click="editUser">确 认</el-button>
  </span>
</el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      rolesList: [],
      dialogVisible:false,
      rightList: [],
      rightsTree: {
          label: 'authName',
          children: 'children'
      },
      defKeys: [],
      roleId: '',
      addUserInfo: false,
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      editUserInfo: false,
      editForm: {
        roleName: '',
        roleDesc: ''
      }
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('/roles')
      if (res.meta.status !== 200) {
        return this.$message.error('角色权限列表失败')
      }
      this.rolesList = res.data
    },
    async delUserRoles(riid,roid) {
      const con = await this.$confirm('此操作将删除该用户此权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch(err => err)
      if(con !== 'confirm') {
          return this.$message.info('取消删除')
      }
      const {data:res} = await this.$http.delete(`roles/${riid.id}/rights/${roid}`)
      if(res.meta.status!==200){
          return this.$message.error('删除权限失败')
      }
      this.$message.success('成功删除该权限')
      riid.children = res.data
    },
    async rolesDialog(role) {
        this.roleId = role.id
        const {data:res} = await this.$http.get('rights/tree')
        if(res.meta.status!==200){
            return this.$message.error('获取权限列表失败！')
        }
        this.rightList = res.data
        this.getleafKeys(role, this.defKeys)
        this.dialogVisible =true
    },
    // 递归获取权限id
    getleafKeys(node, arr) {
        if(!node.children) {
            return arr.push(node.id)
        }
        node.children.forEach(item=>
            this.getleafKeys(item,arr)
        )
    },
    // 关闭对话框时清空列表
    dialogClose() {
        this.defKeys = []
    },
    // 点击确认提交信息
    async dialogTreeInfo() {
        const key = [
            ...this.$refs.treeRef.getCheckedKeys(),
            ...this.$refs.treeRef.getHalfCheckedKeys()
        ]
        const keyStr = key.join(',')
        const {data:res} = await this.$http.post(`roles/${this.roleId}/rights`, {rids: keyStr})
        if(res.meta.status!==200){
            return this.$message.error('角色授权失败！')
        }
        this.$message.success('角色授权成功！')
        this.getRolesList()
        this.dialogVisible = false
    },
    // 添加角色
    addUser() {
      this.$refs.addFormRef.validate(async valid=>{
        if(!valid) return
        const {data:res} = await this.$http.post('/roles',this.addForm)
        if(res.meta.status!==201){
          return this.$message.error('角色添加失败！')
        }
        this.$message.success('角色添加成功！')
        this.addUserInfo = false
        this.getRolesList()
      })
    },
    addRolesClose() {
      this.$refs.addFormRef.resetFields()
    },
    // 编辑角色
    async editRoles(id) {
      const {data:res} = await this.$http.get('/roles/'+id)
      if(res.meta.status!==200) {
        return this.$message.error('查询角色失败！')
      }
      this.editForm = res.data
      this.editUserInfo = true
    },
    // 编辑提交
    editUser() {
      this.$refs.editFormRef.validate(async valid=>{
        if(!valid) return
        const {data:res} = await this.$http.put('/roles/'+this.editForm.roleId, {
          roleName: this.editForm.roleName,
          roleDesc: this.editForm.roleDesc
        })
        if(res.meta.status !== 200) {
          return this.$message.error('修改角色失败！')
        }
        this.$message.success('修改角色成功！')
        this.editUserInfo = false
        this.getRolesList()
      })
    },
    // 删除角色
    async delRoles(id) {
      const confirmUser = await this.$confirm('此操作将永久删除用户，是否继续？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        // 点击取消返回 cancel ，点击确认返回 confirm 
        if(confirmUser!=='confirm') {
          return this.$message.info('取消删除')
        }
      const {data:res} = await this.$http.delete('/roles/'+id)
      if(res.meta.status!==200) {
        return this.$message.error('删除角色失败！')
      }
      this.$message.success('角色删除成功！')
      this.getRolesList()
      console.log(id)
    },
    editRolesClose() {
      this.$refs.editFormRef.resetFields()
    }
  },
}
</script>
<style lang="less">
.el-tag {
  margin: 7px;
}
.el-row {
  display: flex;
  align-items: center;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbtm {
  border-bottom: 1px solid #eee;
}
</style>